package br.com.amadeus.android.activities.course.goal;

import java.util.ArrayList;
import java.util.GregorianCalendar;

import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.adapters.GoalAdapter;
import br.com.amadeus.android.adapters.GoalList;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.entities.Goal;
import br.com.amadeus.android.entities.Task;
import br.com.amadeus.android.util.Util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class HomeGoalActivity extends Activity
{
	private Intent intent;
	private Intent chartIntent;
	private static final int NOVO = 0;
	private static final int GRAFICO = 2;
	private ArrayList<GoalList> listaDeObjetivos;
	private FacadeAmadeusDroid facadeAmadeusDroid = FacadeAmadeusDroid.getInstance(this);
	int course_id;
	
	
	private ListView listView;
	
	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.amadeus_home_goal);
        
    	//video de libras
		ImageButton librasBt = (ImageButton)findViewById(R.id.botaoLibras6);
        librasBt.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent it = new Intent("ABRIR_LIBRAS");
				it.putExtra("video_libras", "HomeGoal.wmv");
				startActivity(it);
				
			}
		});
        intent = new Intent("FORM_GOAL");
        
        Bundle gotBasket = getIntent().getExtras();
        course_id = gotBasket.getInt("course_id");
        intent.putExtra("course_id", course_id);
        
        /*Carregando os objetos no arraylist*/
        
        listaDeObjetivos = new ArrayList<GoalList>();
        ArrayList<Goal> goalArray = facadeAmadeusDroid.getAllGoalByCourse(course_id);
        if( goalArray!= null ){
	        for (int i = 0; i < goalArray.size(); i++) {
	        	GoalList goalList = new GoalList(goalArray.get(i).getId(), goalArray.get(i).getDefinition(), R.id.imgBtnExcluir, R.id.imgBtnEditar);
				listaDeObjetivos.add(goalList);
			}
        }else{
        	Toast.makeText(this, "Nenhum Objetivo!", Toast.LENGTH_LONG);
        }
        //instanciando o baseAdapter chamado ObjetivoAdapter
        AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
        GoalAdapter adapter = new GoalAdapter(this, listaDeObjetivos, alarme, course_id);

        this.listView = (ListView) findViewById(R.id.lvGoals);
        this.listView.setAdapter(adapter);
    }
	
	@Override
	protected void onStop() {
		super.onStop();
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		MenuItem itemNovo = menu.add(0, NOVO, 0, "Novo");
		itemNovo.setIcon(R.drawable.novoitem);

		MenuItem itemgraf = menu.add(0, GRAFICO, 0, "Gráficos");
		itemgraf.setIcon(R.drawable.graficos);
		
		return true;
	}
	
	@TargetApi(8)
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		switch (item.getItemId()) 
		{
			case NOVO:
				startActivity(intent);
				return true;
	
			/*case LISTAGEM:				
				return true;
				*/
			case GRAFICO:
				ArrayList<Goal> goalList = facadeAmadeusDroid.getAllGoalByCourse(course_id);
				if (!goalList.isEmpty()) {
					chartIntent = new Intent("CHART_GOAL");
					Course c = facadeAmadeusDroid.getCourse(course_id);
					ArrayList<Task> taskList;
					int[] plannedList = new int[goalList.size()];
					int[] realizedList = new int[goalList.size()];
					String[] goals = new String[goalList.size()];
					
					GregorianCalendar beginDate;
					GregorianCalendar endDate;
					for (int i = 0; i < goalList.size(); i++) {
						beginDate = Util.stringDatetoGregorianCalendar(goalList.get(i).getBeginDate());
						endDate = Util.stringDatetoGregorianCalendar(goalList.get(i).getEndDate());
						plannedList[i] = Util.getIntervalHours(beginDate, endDate);
						plannedList[i] = (int)(plannedList[i]/24)*(goalList.get(i).getAvgStudyTime()/60);
						goals[i] = goalList.get(i).getDefinition().substring(0, 4);
						taskList = facadeAmadeusDroid.getAllTasksByGoal(goalList.get(i).getId());
						for (int j = 0; j < taskList.size(); j++) {
							int[] temp = new int[taskList.size()];
							beginDate = Util.stringDatetoGregorianCalendar(taskList.get(j).getBeginDate());
							endDate = Util.stringDatetoGregorianCalendar(taskList.get(j).getEndDate());
							temp[j] = Util.getIntervalHours(beginDate, endDate);
							for (int k = 0; k < temp.length; k++) {
								realizedList[i] += temp[k];
							}
						}
					}
					
					Bundle chartBasket = new Bundle();
					chartBasket.putInt("course_id", course_id);
					chartBasket.putCharSequence("course", c.getName());
					chartBasket.putIntArray("planned", plannedList);
					chartBasket.putIntArray("realized", realizedList);
					chartBasket.putCharSequenceArray("goals", goals);
					chartIntent.putExtras(chartBasket);
					startActivity(chartIntent);
					return true;
				}else{
					AlertDialog.Builder dialog = new AlertDialog.Builder(this);
					dialog.setMessage("Antes você deve definir seu objetivo e planejar suas tarefas para poder visualiza-las no Gráfico.");
					dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							try {
								this.finalize();
							} catch (Throwable e) {
								e.printStackTrace();
							}
							
						}
					});
					dialog.show();
				}
		}	
		
		return false;
	}
	
	//setando os conteúdos de cada linha da listview
	public void cadastrarObjetivo()
	{
		Intent it = getIntent();
		GoalList goal = new GoalList();
   	 	
		goal.setId(1);
   	 	goal.setImg(R.id.imgBtnEditar);        	 
   	 	goal.setImgExluir(R.id.imgBtnExcluir);
   	 	goal.setNome(it.getStringExtra("objetivo"));
   	 	listaDeObjetivos.add(goal);
	}
}